<template>
  <div v-if="form.address != ''">
    <!-- 随着鼠标的滚动缩放 -->
    <baidu-map class="bm-view"
               :center="center"
               :zoom="zoom"
               :scroll-wheel-zoom="true"
               @ready="createMap">
      <!-- 标记 -->
      <bm-marker :position="{lng: form.longitude, lat: form.latitude}"/>
    </baidu-map>

  </div>
</template>

<script>
import {getProductList} from "@/api/detail";

export default {
  name: 'Map',
  data() {
    return {
      form: {
        longitude: '',
        latitude: '',
        address: ''
      },
      center: {lng: 0, lat: 0},
      zoom: 15,
      deviceData: this.$route.query.rows,
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      getProductList({did: this.deviceData.id}).then(res => {
        let info = res.data;
        this.form.longitude = info.longitude;
        this.form.latitude = info.latitude;
        this.form.address = info.address;
      })
    },
    createMap({ BMap, map }) {
      this.BMap = BMap;
      this.map = map;
      this.scanMap();
    },
    scanMap() {
      this.map.clearOverlays();
      if (this.form.longitude != "" && this.form.latitude != "") {
        this.center.lng = this.form.longitude;
        this.center.lat = this.form.latitude;

        // 根据经纬度创建点坐标
        let point = new this.BMap.Point(this.form.longitude, this.form.latitude);
        this.map.centerAndZoom(point, 17);
        let marker = new this.BMap.Marker(point); // 创建标注
        this.map.addOverlay(marker); // 将标注添加到地图中
        this.zoom = 17;
      } else {
        // 默认地址
        this.center = {
          lng: 113.657804,
          lat: 34.727476,
        };
        // 根据经纬度创建点坐标
        let point = new this.BMap.Point(113.657804, 34.727476);
      }

    },
  }
}
</script>

<style scoped>
.bm-view {
  width: 100%;
  height: 465px;
}
</style>
